package com.pig4cloud.pig.demo.Service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.demo.Mapper.ArticleMapper;
import com.pig4cloud.pig.demo.Mapper.CompanyMapper;
import com.pig4cloud.pig.demo.Service.ArticleService;
import com.pig4cloud.pig.demo.Service.TitleService;
import com.pig4cloud.pig.demo.feign.Entity.Article;
import com.pig4cloud.pig.demo.feign.Entity.Company;
import com.pig4cloud.pig.demo.feign.vo.MyArticleVO;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.AnalyzeRequest;
import org.elasticsearch.client.indices.AnalyzeResponse;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TitleService titleService;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Value("${article.index}")
    private String articleIndex;

    @Override
    public int insertArticle(Article article) {
        return articleMapper.insert(article);
    }

    @Override
    public String findArticleContentById(Long id) throws IOException {
        GetRequest request = new GetRequest(articleIndex, id.toString());
        GetResponse doc = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        if (doc.isExists()) {
//            Object content = doc.getSourceAsMap().get("content");
//            System.out.println(content);
//            System.out.println("===========================");
//            System.out.println(content.toString());
            return doc.getSourceAsMap().get("content").toString();
        }
        return null;
    }

    @Override
    public long findCategoryCount(String category) throws IOException {
        Long id = titleService.findByCategory(category);
        if (id == null)
            return 0;

        SearchRequest request = new SearchRequest(articleIndex);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        searchSourceBuilder.query(QueryBuilders.termQuery("tid", id));
        request.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        return response.getHits().getTotalHits().value;
    }

    @Override
    public List<Map<String, Object>> pagingQuery(String category, int start, int size) throws IOException {
        Long id = titleService.findByCategory(category);

        SearchRequest request = new SearchRequest(articleIndex);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        boolQueryBuilder
                .must(QueryBuilders.termQuery("tid",id))
                .should(QueryBuilders.wildcardQuery("title",category.toLowerCase()));
        searchSourceBuilder.query(boolQueryBuilder);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style ='color:red;font-weight: bold'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        searchSourceBuilder.from(start);
        searchSourceBuilder.size(size);

        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        List<Map<String, Object>> lists = new ArrayList<>();
        for (SearchHit hit : search.getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            HighlightField title = highlightFields.get("title");

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title != null) {
                Text[] fragments = title.getFragments();

                String newStr = "";
                for (Text fragment : fragments) {
                    newStr += fragment;
                }
                sourceAsMap.put("title", newStr);
            }
            lists.add(sourceAsMap);
        }

        return lists;
    }

    @Override
    public Article findById(Long id) {
        return null;
    }

    @Override
    public List<Map<String, Object>> searchByKeyword(String keyword) throws IOException {
        SearchRequest request = new SearchRequest(articleIndex);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.termQuery("title", keyword));
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        searchSourceBuilder.highlighter(highlightBuilder);

        request.source(searchSourceBuilder);
        SearchResponse search = restHighLevelClient.search(request, RequestOptions.DEFAULT);

        List<Map<String, Object>> lists = new ArrayList<>();
        for (SearchHit hit : search.getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();

            HighlightField title = highlightFields.get("title");

            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            if (title != null) {
                Text[] fragments = title.getFragments();
                String newTitle = "";

                for (Text fragment : fragments) {
                    newTitle += fragment;
                }
                sourceAsMap.put("title", newTitle);
            }
            lists.add(hit.getSourceAsMap());
        }
        return lists;
    }

    @Override
    public List<MyArticleVO> queryMyArticleVO(Long userId){
        return articleMapper.queryMyArticleVO(userId);
    }
}
